// 策略服务文件 - 存放各种交易策略算法
import axios from 'axios'

// 计算移动平均线
export const calculateMA = (data, period) => {
  const ma = []
  for (let i = period - 1; i < data.length; i++) {
    let sum = 0
    for (let j = 0; j < period; j++) {
      sum += data[i - j].close
    }
    ma.push(sum / period)
  }
  return ma
}

// 计算RSI
export const calculateRSI = (data, period) => {
  if (data.length < period + 1) return []
  
  const rsi = []
  const gains = []
  const losses = []
  
  // 计算每日涨跌
  for (let i = 1; i < data.length; i++) {
    const change = data[i].close - data[i-1].close
    gains.push(change > 0 ? change : 0)
    losses.push(change < 0 ? Math.abs(change) : 0)
  }
  
  // 计算初始平均值
  let avgGain = gains.slice(0, period).reduce((a, b) => a + b, 0) / period
  let avgLoss = losses.slice(0, period).reduce((a, b) => a + b, 0) / period
  
  for (let i = period; i < gains.length; i++) {
    const rs = avgLoss === 0 ? 100 : avgGain / avgLoss
    const rsiValue = 100 - (100 / (1 + rs))
    rsi.push(rsiValue)
    
    // 更新平均值（使用指数平滑）
    avgGain = (avgGain * (period - 1) + gains[i]) / period
    avgLoss = (avgLoss * (period - 1) + losses[i]) / period
  }
  
  return rsi
}

// 计算布林带
export const calculateBollingerBands = (data, period, stdDevMultiplier) => {
  if (data.length < period) return []
  
  const bands = []
  
  for (let i = period - 1; i < data.length; i++) {
    // 计算中轨（移动平均线）
    let sum = 0
    for (let j = 0; j < period; j++) {
      sum += data[i - j].close
    }
    const middle = sum / period
    
    // 计算标准差
    let variance = 0
    for (let j = 0; j < period; j++) {
      const diff = data[i - j].close - middle
      variance += diff * diff
    }
    const stdDev = Math.sqrt(variance / period)
    
    // 计算上下轨
    const upper = middle + (stdDev * stdDevMultiplier)
    const lower = middle - (stdDev * stdDevMultiplier)
    
    bands.push({ upper, middle, lower })
  }
  
  return bands
}

// 计算VWAP (成交量加权平均价格)
export const calculateVWAP = (data) => {
  try {
    // 参数验证
    if (!data || !Array.isArray(data) || data.length === 0) {
      console.warn('VWAP计算失败：输入数据为空或无效')
      return []
    }
    
    const vwap = []
    let cumulativePriceVolume = 0
    let cumulativeVolume = 0
    
    console.log(`开始计算VWAP，输入数据共${data.length}条`)
    
    for (let i = 0; i < data.length; i++) {
      // 检查数据完整性
      if (data[i] === null || data[i] === undefined) {
        console.warn(`VWAP计算警告：数据索引${i}处的数据为空`)
        continue
      }
      
      // 检查必要字段是否存在
      if (data[i].high === undefined || data[i].low === undefined || 
          data[i].close === undefined || data[i].volume === undefined) {
        console.warn(`VWAP计算警告：数据索引${i}缺少必要字段 (high, low, close, volume)`)
        continue
      }
      
      // 检查数据类型
      if (typeof data[i].high !== 'number' || typeof data[i].low !== 'number' || 
          typeof data[i].close !== 'number' || typeof data[i].volume !== 'number') {
        console.warn(`VWAP计算警告：数据索引${i}的字段类型不正确`)
        continue
      }
      
      // 计算典型价格 (典型价格 = (最高价 + 最低价 + 收盘价) / 3)
      // 典型价格代表了该K线周期内的平均价格水平
      const typicalPrice = (data[i].high + data[i].low + data[i].close) / 3
      
      // 检查典型价格计算结果
      if (!isFinite(typicalPrice)) {
        console.warn(`VWAP计算警告：索引${i}处的典型价格计算结果无效`)
        continue
      }
      
      // 获取成交量数据，如果成交量为0则设为1防止除零错误
      // 成交量反映了该周期内交易的活跃程度
      const volume = data[i].volume || 1
      
      // 累积价格*成交量和成交量
      // 价格*成交量表示该周期内的总交易价值
      cumulativePriceVolume += typicalPrice * volume
      cumulativeVolume += volume
      
      // 计算当前VWAP值
      // VWAP = 累积(典型价格 * 成交量) / 累积成交量
      if (cumulativeVolume > 0) {
        const vwapValue = cumulativePriceVolume / cumulativeVolume
        if (isFinite(vwapValue)) {
          vwap.push(vwapValue)
          // 打印每次计算的VWAP参数
          console.log(`VWAP计算[${i}] - 典型价格: ${typicalPrice.toFixed(4)}, 成交量: ${volume}, 累积价格*成交量: ${cumulativePriceVolume.toFixed(4)}, 累积成交量: ${cumulativeVolume}, VWAP: ${vwapValue.toFixed(4)}`)
        } else {
          console.warn(`VWAP计算警告：索引${i}处计算出的VWAP值无效`)
          vwap.push(typicalPrice)
        }
      } else {
        vwap.push(typicalPrice)
        // 打印每次计算的VWAP参数
        console.log(`VWAP计算[${i}] - 典型价格: ${typicalPrice.toFixed(4)}, 成交量: ${volume}, 累积价格*成交量: ${cumulativePriceVolume.toFixed(4)}, 累积成交量: ${cumulativeVolume}, VWAP: ${typicalPrice.toFixed(4)}(使用典型价格)`)
      }
    }
    
    // 输出计算结果信息
    console.log(`VWAP计算完成：输入数据${data.length}条，有效计算${vwap.length}条`)
    
    return vwap
  } catch (error) {
    console.error('VWAP计算过程中发生错误：', error)
    return []
  }
}

// MA交叉策略
export const runMACrossStrategy = (data, settings) => {
  const results = {
    equityCurve: [],
    trades: []
  }
  
  const fastMA = settings.fastMAPeriod
  const slowMA = settings.slowMAPeriod
  const capital = settings.initialCapital
  const tradePercent = settings.tradeAmount / 100
  const stopLoss = settings.stopLoss / 100
  const takeProfit = settings.takeProfit / 100
  
  let position = 0 // 持仓数量
  let cash = capital // 现金
  let lastBuyPrice = 0
  
  // 计算MA
  const fastMAs = calculateMA(data, fastMA)
  const slowMAs = calculateMA(data, slowMA)
  
  // 确保有足够的数据计算MA
  if (fastMAs.length === 0 || slowMAs.length === 0) {
    console.warn('MA计算失败，数据不足')
    return results
  }
  
  for (let i = 1; i < Math.min(fastMAs.length, slowMAs.length); i++) {
    const dataIndex = i + slowMA - 1
    if (dataIndex >= data.length) break
    
    const currentPrice = data[dataIndex].close
    const currentDate = data[dataIndex].date
    
    // 检查交易信号
    const buySignal = fastMAs[i] > slowMAs[i] && fastMAs[i-1] <= slowMAs[i-1]
    const sellSignal = fastMAs[i] < slowMAs[i] && fastMAs[i-1] >= slowMAs[i-1]
    
    // 检查止损止盈
    const stopLossTriggered = position > 0 && currentPrice <= lastBuyPrice * (1 - stopLoss)
    const takeProfitTriggered = position > 0 && currentPrice >= lastBuyPrice * (1 + takeProfit)
    
    if (buySignal && position === 0 && cash > 0) {
      // 买入
      const tradeValue = cash * tradePercent
      const amount = tradeValue / currentPrice
      position = amount
      cash -= tradeValue
      lastBuyPrice = currentPrice
      
      results.trades.push({
        date: currentDate,
        type: 'buy',
        price: currentPrice,
        amount: amount,
        value: tradeValue
      })
    } else if ((sellSignal || stopLossTriggered || takeProfitTriggered) && position > 0) {
      // 卖出
      const sellAmount = position
      const tradeValue = sellAmount * currentPrice
      const profit = tradeValue - (sellAmount * lastBuyPrice)
      cash += tradeValue
      position = 0
      
      results.trades.push({
        date: currentDate,
        type: 'sell',
        price: currentPrice,
        amount: sellAmount,
        value: tradeValue,
        profit: profit
      })
    }
    
    // 更新权益曲线
    const totalEquity = cash + (position * currentPrice)
    results.equityCurve.push({
      date: currentDate,
      equity: totalEquity
    })
  }
  
  return results
}

// RSI策略
export const runRSIStrategy = (data, settings) => {
  const results = {
    equityCurve: [],
    trades: []
  }
  
  const capital = settings.initialCapital
  const tradePercent = settings.tradeAmount / 100
  const rsiPeriod = settings.rsiPeriod
  const overbought = settings.overbought
  const oversold = settings.oversold
  const stopLoss = settings.stopLoss / 100
  const takeProfit = settings.takeProfit / 100
  
  let position = 0
  let cash = capital
  let lastBuyPrice = 0
  
  // 计算RSI
  const rsiValues = calculateRSI(data, rsiPeriod)
  
  if (rsiValues.length === 0) {
    console.warn('RSI计算失败，数据不足')
    return results
  }
  
  for (let i = 1; i < rsiValues.length; i++) {
    const dataIndex = i + rsiPeriod
    if (dataIndex >= data.length) break
    
    const currentPrice = data[dataIndex].close
    const currentDate = data[dataIndex].date
    const currentRSI = rsiValues[i]
    const prevRSI = rsiValues[i-1]
    
    // RSI交易信号
    const buySignal = prevRSI <= oversold && currentRSI > oversold && position === 0
    const sellSignal = prevRSI >= overbought && currentRSI < overbought && position > 0
    
    // 检查止损止盈
    const stopLossTriggered = position > 0 && currentPrice <= lastBuyPrice * (1 - stopLoss)
    const takeProfitTriggered = position > 0 && currentPrice >= lastBuyPrice * (1 + takeProfit)
    
    if (buySignal && cash > 0) {
      // 买入
      const tradeValue = cash * tradePercent
      const amount = tradeValue / currentPrice
      position = amount
      cash -= tradeValue
      lastBuyPrice = currentPrice
      
      results.trades.push({
        date: currentDate,
        type: 'buy',
        price: currentPrice,
        amount: amount,
        value: tradeValue
      })
    } else if ((sellSignal || stopLossTriggered || takeProfitTriggered) && position > 0) {
      // 卖出
      const sellAmount = position
      const tradeValue = sellAmount * currentPrice
      const profit = tradeValue - (sellAmount * lastBuyPrice)
      cash += tradeValue
      position = 0
      
      results.trades.push({
        date: currentDate,
        type: 'sell',
        price: currentPrice,
        amount: sellAmount,
        value: tradeValue,
        profit: profit
      })
    }
    
    // 更新权益曲线
    const totalEquity = cash + (position * currentPrice)
    results.equityCurve.push({
      date: currentDate,
      equity: totalEquity
    })
  }
  
  return results
}

// 布林带策略
export const runBollingerStrategy = (data, settings) => {
  const results = {
    equityCurve: [],
    trades: []
  }
  
  const capital = settings.initialCapital
  const tradePercent = settings.tradeAmount / 100
  const bbPeriod = settings.bbPeriod
  const bbStdDev = settings.bbStdDev
  const stopLoss = settings.stopLoss / 100
  const takeProfit = settings.takeProfit / 100
  
  let position = 0
  let cash = capital
  let lastBuyPrice = 0
  
  // 计算布林带
  const bollingerBands = calculateBollingerBands(data, bbPeriod, bbStdDev)
  
  if (bollingerBands.length === 0) {
    console.warn('布林带计算失败，数据不足')
    return results
  }
  
  for (let i = 0; i < bollingerBands.length; i++) {
    const dataIndex = i + bbPeriod - 1
    if (dataIndex >= data.length) break
    
    const currentPrice = data[dataIndex].close
    const currentDate = data[dataIndex].date
    const { upper, lower, middle } = bollingerBands[i]
    
    // 布林带交易信号
    const buySignal = currentPrice <= lower && position === 0  // 价格触及下轨
    const sellSignal = currentPrice >= upper && position > 0   // 价格触及上轨
    
    // 检查止损止盈
    const stopLossTriggered = position > 0 && currentPrice <= lastBuyPrice * (1 - stopLoss)
    const takeProfitTriggered = position > 0 && currentPrice >= lastBuyPrice * (1 + takeProfit)
    
    if (buySignal && cash > 0) {
      // 买入
      const tradeValue = cash * tradePercent
      const amount = tradeValue / currentPrice
      position = amount
      cash -= tradeValue
      lastBuyPrice = currentPrice
      
      results.trades.push({
        date: currentDate,
        type: 'buy',
        price: currentPrice,
        amount: amount,
        value: tradeValue
      })
    } else if ((sellSignal || stopLossTriggered || takeProfitTriggered) && position > 0) {
      // 卖出
      const sellAmount = position
      const tradeValue = sellAmount * currentPrice
      const profit = tradeValue - (sellAmount * lastBuyPrice)
      cash += tradeValue
      position = 0
      
      results.trades.push({
        date: currentDate,
        type: 'sell',
        price: currentPrice,
        amount: sellAmount,
        value: tradeValue,
        profit: profit
      })
    }
    
    // 更新权益曲线
    const totalEquity = cash + (position * currentPrice)
    results.equityCurve.push({
      date: currentDate,
      equity: totalEquity
    })
  }
  
  return results
}

// 自定义策略
export const runCustomStrategy = (data, settings) => {
  const results = {
    equityCurve: [],
    trades: []
  }
  
  const capital = settings.initialCapital
  const tradePercent = settings.tradeAmount / 100
  const stopLoss = settings.stopLoss / 100
  const takeProfit = settings.takeProfit / 100
  
  let position = 0
  let cash = capital
  let lastBuyPrice = 0
  
  // 简单的动量 + 价格突破策略
  for (let i = 5; i < data.length; i++) {
    const currentPrice = data[i].close
    const currentDate = data[i].date
    const currentVolume = data[i].volume
    
    // 计算近5日平均价格和成交量
    const avgPrice = data.slice(i-5, i).reduce((sum, d) => sum + d.close, 0) / 5
    const avgVolume = data.slice(i-5, i).reduce((sum, d) => sum + d.volume, 0) / 5
    
    // 交易信号：价格突破平均线 + 成交量放大
    const priceBreakout = currentPrice > avgPrice * 1.02 // 价格突破上方2%
    const volumeSpike = currentVolume > avgVolume * 1.5  // 成交量放大1.5倍
    const buySignal = priceBreakout && volumeSpike && position === 0
    
    const priceDrop = currentPrice < avgPrice * 0.98    // 价格跌破下方2%
    const sellSignal = priceDrop && position > 0
    
    // 检查止损止盈
    const stopLossTriggered = position > 0 && currentPrice <= lastBuyPrice * (1 - stopLoss)
    const takeProfitTriggered = position > 0 && currentPrice >= lastBuyPrice * (1 + takeProfit)
    
    if (buySignal && cash > 0) {
      // 买入
      const tradeValue = cash * tradePercent
      const amount = tradeValue / currentPrice
      position = amount
      cash -= tradeValue
      lastBuyPrice = currentPrice
      
      results.trades.push({
        date: currentDate,
        type: 'buy',
        price: currentPrice,
        amount: amount,
        value: tradeValue
      })
    } else if ((sellSignal || stopLossTriggered || takeProfitTriggered) && position > 0) {
      // 卖出
      const sellAmount = position
      const tradeValue = sellAmount * currentPrice
      const profit = tradeValue - (sellAmount * lastBuyPrice)
      cash += tradeValue
      position = 0
      
      results.trades.push({
        date: currentDate,
        type: 'sell',
        price: currentPrice,
        amount: sellAmount,
        value: tradeValue,
        profit: profit
      })
    }
    
    // 更新权益曲线
    const totalEquity = cash + (position * currentPrice)
    results.equityCurve.push({
      date: currentDate,
      equity: totalEquity
    })
  }
  
  return results
}

// VWAP策略
export const runVWAPStrategy = (data, settings) => {
  try {
    console.log('开始执行VWAP策略回测')
    
    const results = {
      equityCurve: [],
      trades: []
    }
    
    // 参数验证
    if (!data || !Array.isArray(data) || data.length === 0) {
      console.warn('VWAP策略回测失败：输入数据为空或无效')
      return results
    }
    
    const capital = settings.initialCapital
    const tradePercent = settings.tradeAmount / 100
    const stopLoss = settings.stopLoss / 100
    const takeProfit = settings.takeProfit / 100
    
    // 参数有效性检查
    if (capital <= 0 || tradePercent <= 0 || tradePercent > 1) {
      console.warn('VWAP策略回测参数无效')
      return results
    }
    
    console.log(`VWAP策略参数：初始资金${capital}，交易比例${tradePercent}，止损${stopLoss}，止盈${takeProfit}`)
    
    let position = 0
    let cash = capital
    let lastBuyPrice = 0
    
    // 计算VWAP
    console.log(`开始计算VWAP，输入数据${data.length}条`)
    const vwapValues = calculateVWAP(data)
    
    if (vwapValues.length === 0) {
      console.warn('VWAP计算失败，数据不足')
      return results
    }
    
    console.log(`VWAP计算完成，得到${vwapValues.length}条VWAP数据`)
    
    let validSignals = 0
    let buySignals = 0
    let sellSignals = 0
    
    for (let i = 1; i < vwapValues.length; i++) {
      const dataIndex = i
      if (dataIndex >= data.length) {
        console.warn(`数据索引超出范围：${dataIndex} >= ${data.length}`)
        break
      }
      
      // 检查数据完整性
      if (!data[dataIndex] || data[dataIndex].close === undefined || 
          data[dataIndex].date === undefined) {
        console.warn(`索引${dataIndex}处的数据不完整`)
        continue
      }
      
      const currentPrice = data[dataIndex].close
      const currentDate = data[dataIndex].date
      const currentVWAP = vwapValues[i]
      const prevVWAP = vwapValues[i-1]
      
      // 打印VWAP参数
      console.log(`VWAP策略参数[${dataIndex}] - 日期: ${currentDate}, 当前价格: ${currentPrice.toFixed(4)}, 当前VWAP: ${currentVWAP.toFixed(4)}, 前一个VWAP: ${prevVWAP.toFixed(4)}, 持仓: ${position}, 现金: ${cash.toFixed(2)}`)
      
      // 检查数值有效性
      if (!isFinite(currentPrice) || !isFinite(currentVWAP) || !isFinite(prevVWAP)) {
        console.warn(`索引${dataIndex}处的价格或VWAP值无效`)
        continue
      }
      
      // VWAP交易信号
      // 买入信号：当前价格上穿VWAP线 且 前一个VWAP值大于等于当前VWAP值 且 当前无持仓
      const buySignal = currentPrice > currentVWAP && prevVWAP >= currentVWAP && position === 0
      // 卖出信号：当前价格下穿VWAP线 且 前一个VWAP值小于等于当前VWAP值 且 当前有持仓
      const sellSignal = currentPrice < currentVWAP && prevVWAP <= currentVWAP && position > 0
      
      // 检查止损止盈
      const stopLossTriggered = position > 0 && currentPrice <= lastBuyPrice * (1 - stopLoss)
      const takeProfitTriggered = position > 0 && currentPrice >= lastBuyPrice * (1 + takeProfit)
      
      if (buySignal && cash > 0) {
        validSignals++
        buySignals++
        console.log(`生成买入信号 - 日期: ${currentDate}, 价格: ${currentPrice}, VWAP: ${currentVWAP}`)
        
        // 买入
        const tradeValue = cash * tradePercent
        const amount = tradeValue / currentPrice
        position = amount
        cash -= tradeValue
        lastBuyPrice = currentPrice
        
        console.log(`执行买入 - 金额: ${tradeValue}, 数量: ${amount}, 剩余资金: ${cash}`)
        
        results.trades.push({
          date: currentDate,
          type: 'buy',
          price: currentPrice,
          amount: amount,
          value: tradeValue,
          reason: '价格上穿VWAP'
        })
      } else if ((sellSignal || stopLossTriggered || takeProfitTriggered) && position > 0) {
        validSignals++
        sellSignals++
        
        const signalType = stopLossTriggered ? '止损' : 
                          takeProfitTriggered ? '止盈' : 
                          '价格下穿VWAP'
        console.log(`生成卖出信号 - 日期: ${currentDate}, 价格: ${currentPrice}, VWAP: ${currentVWAP}, 类型: ${signalType}`)
        
        // 卖出
        const sellAmount = position
        const tradeValue = sellAmount * currentPrice
        const profit = tradeValue - (sellAmount * lastBuyPrice)
        cash += tradeValue
        position = 0
        
        console.log(`执行卖出 - 金额: ${tradeValue}, 利润: ${profit}, 总资金: ${cash}`)
        
        const sellReason = stopLossTriggered ? '止损' : 
                          takeProfitTriggered ? '止盈' : 
                          '价格下穿VWAP'
        
        results.trades.push({
          date: currentDate,
          type: 'sell',
          price: currentPrice,
          amount: sellAmount,
          value: tradeValue,
          profit: profit,
          reason: sellReason
        })
      }
      
      // 更新权益曲线
      const totalEquity = cash + (position * currentPrice)
      results.equityCurve.push({
        date: currentDate,
        equity: totalEquity
      })
    }
    
    console.log(`VWAP策略回测完成：总共${validSignals}个有效信号，买入${buySignals}次，卖出${sellSignals}次`)
    console.log(`最终结果：现金${cash}，持仓${position}，总权益${cash + (position * (data.length > 0 ? data[data.length-1].close : 0))}`)
    
    return results
  } catch (error) {
    console.error('VWAP策略回测过程中发生错误：', error)
    return {
      equityCurve: [],
      trades: []
    }
  }
}

// 获取历史数据
export const fetchHistoricalData = async (symbol, period, interval, dataSource) => {
  // 根据用户选择决定使用真实数据还是模拟数据
  if (dataSource === 'real') {
    try {
      // 尝试获取真实历史数据
      const realData = await fetchRealHistoricalData(symbol, period, interval)
      if (realData && realData.length > 0) {
        return realData
      }
    } catch (error) {
      console.warn('获取真实数据失败，使用模拟数据:', error.message)
    }
  }
  
  // 使用模拟数据
  return generateMockHistoricalData(symbol, period, interval)
}

// 获取真实历史数据
export const fetchRealHistoricalData = async (symbol, period, interval) => {
  const symbolMap = {
    'BTC/USDT': { binance: 'BTCUSDT', coingecko: 'bitcoin', cryptocompare: 'BTC' },
    'ETH/USDT': { binance: 'ETHUSDT', coingecko: 'ethereum', cryptocompare: 'ETH' },
    'BNB/USDT': { binance: 'BNBUSDT', coingecko: 'binancecoin', cryptocompare: 'BNB' },
    'SOL/USDT': { binance: 'SOLUSDT', coingecko: 'solana', cryptocompare: 'SOL' }
  }
  
  const coinInfo = symbolMap[symbol]
  if (!coinInfo) {
    throw new Error(`不支持的交易对: ${symbol}`)
  }
  
  // 转换周期为天数
  let days = 30
  if (period === '7d') days = 7
  else if (period === '30d') days = 30
  else if (period === '90d') days = 90
  else if (period === '1y') days = 365
  
  // 转换时间间隔
  let binanceInterval = '1d'
  if (interval === '1h') binanceInterval = '1h'
  else if (interval === '4h') binanceInterval = '4h'
  else if (interval === '1d') binanceInterval = '1d'
  
  // 优先使用Binance API（数据质量最高）
  try {
    const response = await axios.get('https://api.binance.com/api/v3/klines', {
      params: {
        symbol: coinInfo.binance,
        interval: binanceInterval,
        limit: Math.min(days, 1000) // Binance最多返回1000条数据
      },
      timeout: 15000
    })
    
    if (response.data && response.data.length > 0) {
      const data = response.data.map(item => ({
        date: new Date(item[0]).toISOString().split('T')[0],
        open: parseFloat(item[1]),
        high: parseFloat(item[2]),
        low: parseFloat(item[3]),
        close: parseFloat(item[4]),
        volume: parseFloat(item[5])
      }))
      
      console.log(`成功从 Binance 获取 ${data.length} 条数据`)
      return data
    }
  } catch (error) {
    console.warn('Binance API失败:', error.message)
  }
  
  // 备用：CryptoCompare API
  try {
    const response = await axios.get('https://min-api.cryptocompare.com/data/v2/histoday', {
      params: {
        fsym: coinInfo.cryptocompare,
        tsym: 'USD',
        limit: Math.min(days, 2000)
      },
      timeout: 15000
    })
    
    if (response.data && response.data.Data && response.data.Data.Data) {
      const data = response.data.Data.Data.map(item => ({
        date: new Date(item.time * 1000).toISOString().split('T')[0],
        open: item.open,
        high: item.high,
        low: item.low,
        close: item.close,
        volume: item.volumeto
      }))
      
      console.log(`成功从 CryptoCompare 获取 ${data.length} 条数据`)
      return data
    }
  } catch (error) {
    console.warn('CryptoCompare API失败:', error.message)
  }
  
  // 备用：CoinGecko API
  try {
    const response = await axios.get(`https://api.coingecko.com/api/v3/coins/${coinInfo.coingecko}/market_chart`, {
      params: {
        vs_currency: 'usd',
        days: days,
        interval: days > 90 ? 'daily' : 'daily'
      },
      timeout: 10000
    })
    
    if (response.data && response.data.prices) {
      return response.data.prices.map((item, index) => {
        const date = new Date(item[0]).toISOString().split('T')[0]
        const price = item[1]
        // CoinGecko只提供价格，我们需要模拟OHLC
        const variation = 0.02 // 2%的变化范围
        return {
          date,
          open: price * (1 + (Math.random() - 0.5) * variation),
          high: price * (1 + Math.random() * variation),
          low: price * (1 - Math.random() * variation),
          close: price,
          volume: 1000 + Math.random() * 2000
        }
      })
    }
  } catch (error) {
    console.warn('CoinGecko API失败:', error.message)
  }
  
  throw new Error('所有真实数据源都无法访问')
}

// 生成模拟历史数据（备用）
export const generateMockHistoricalData = (symbol, period, interval) => {
  const data = []
  const now = new Date()
  let days = 30
  
  if (period === '7d') days = 7
  else if (period === '30d') days = 30
  else if (period === '90d') days = 90
  else if (period === '1y') days = 365
  
  const basePrice = symbol === 'BTC/USDT' ? 45000 : 
                   symbol === 'ETH/USDT' ? 3000 : 
                   symbol === 'BNB/USDT' ? 400 : 150
  
  let currentPrice = basePrice
  let trend = 1 // 1为上涨趋势，-1为下跌趋势
  let trendDays = 0
  
  for (let i = 0; i < days; i++) {
    const date = new Date(now)
    date.setDate(date.getDate() - (days - i))
    
    // 每5-10天改变一次趋势
    if (trendDays > 5 + Math.random() * 5) {
      trend *= -1
      trendDays = 0
    }
    
    // 根据趋势调整价格
    const trendChange = trend * (0.005 + Math.random() * 0.015) // 0.5-2%的趋势变化
    const randomChange = (Math.random() - 0.5) * 0.01 // ±0.5%的随机波动
    
    currentPrice *= (1 + trendChange + randomChange)
    
    const open = currentPrice * (0.99 + Math.random() * 0.02)
    const close = currentPrice
    const high = Math.max(open, close) * (1 + Math.random() * 0.01)
    const low = Math.min(open, close) * (1 - Math.random() * 0.01)
    const volume = 500 + Math.random() * 1000
    
    data.push({
      date: date.toISOString().split('T')[0],
      open,
      high,
      low,
      close,
      volume
    })
    
    trendDays++
  }
  
  return data
}